package cbacba.server.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cbacba.server.CbaJSONGenerator;
import cbacba.server.PMF;
import cbacba.shared.CbaPage;
import cbacba.shared.CbaResult;

public class CbaCount extends HttpServlet {
    private static final long serialVersionUID = -2841949752103124573L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String url = req.getParameter("url");
        String decode = URLDecoder.decode(url, "UTF-8").toLowerCase();
        boolean validUrl = decode.startsWith("http://") || decode.startsWith("https://");

        CbaResult result = new CbaResult();

        PersistenceManager manager = PMF.get().getPersistenceManager();
        CbaPage cbaPage = null;
        try {
            cbaPage = manager.getObjectById(CbaPage.class, url);
        } catch (JDOException e) {
            cbaPage = new CbaPage();
            cbaPage.setUrlEncoded(url);
        }

        try {
            String hasToCountExp = req.getParameter("count");
            boolean hasToCount = false;
            if (hasToCountExp != null) {
                hasToCount = validUrl && hasToCountExp.trim().toLowerCase().equals("true");
            }

            String isAlreadyCbaed = (String) req.getSession().getAttribute(url);

            if (hasToCount) {
                if (isAlreadyCbaed != null) {
                    result.setState(CbaResult.STATE_DUPLICATED_CBA);
                }

                else {
                    cbaPage.increaseCount();
                    manager.makePersistent(cbaPage);
                    req.getSession().setAttribute(url, "true");
                }
            }
            if (validUrl) {
                result.setCount(cbaPage.getCbaCount());
            }else{
                result.setState(CbaResult.STATE_INVALID_CBA);
                result.setCount(0);
            }
        } finally {
            manager.close();
        }

        resp.getWriter().write(new CbaJSONGenerator().generate(result));
    }

}
